<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Title</title>
  <style>
    body {
      margin: 0;
      height: 100vh;
      background: #1a2b3c;
    }
  </style>
</head>
<body>

</body>
<script>
  const api = time => new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(time)
      // reject(new Error('错误'))
    }, time)
  });

  const concurrence = (target, maxNum = 3) => new Promise(resolve => {
    if (!target.length) {
      resolve([])
      return
    }
    const result = []
    let index = 0,
        count = 0;
    const request = async () => {
      if (index >= target.length) {
        return
      }
      const idx = index
      index++
      const currentTime = target[idx]
      try {
        const res = await api(currentTime)
        result[idx] = res
        console.log('进入 try---->>', res)
      } catch (err) {
        console.log('进入 catch --->>', err)
        if (err instanceof Error) {
          result[idx] = err.message
          return
        }
        result[idx] = err.toString()
      } finally {
        console.log('进入 finally')
        count++;
        if (count === target.length) {
          resolve(result)
        } else {
          await request()
        }
      }
    }
    const lim = Math.min(target.length, maxNum)
    for (let i = 0; i < lim; i++) {
      request()
      console.log('初次执行 request', i)
    }
  })

  concurrence([500, 1000, 1500, 2000, 2500, 3000], 3).then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err)
  })

</script>
</html>